<template>
  <!--应付单-->
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-row>
        <el-col :span="6">
          <!--<el-button class="filter-item" size="small" style="margin-left: 10px;"-->
                     <!--@click="handleCreate" type="primary" icon="el-icon-plus">添加-->
          <!--</el-button>-->
          <!--<el-button class="filter-item" size="small" style="margin-left: 10px;"-->
                     <!--@click="handleUpdate" type="primary" icon="el-icon-edit">编辑-->
          <!--</el-button>-->
          <el-button class="filter-item" size="small" style="margin-left: 10px;" @click="handleConfirm" type="primary"
                     icon="el-icon-view">审核
          </el-button>
          <el-button class="filter-item" size="small" style="margin-left: 10px;" @click="handleDelete" type="primary"
                     icon="el-icon-delete">删除
          </el-button>
          <el-button class="filter-item" size="small" style="margin-left: 10px;" @click="handleFresh" type="primary"
                     icon="el-icon-refresh">手动抓取
          </el-button>
        </el-col>
        <el-col :span="18" style="text-align: right">
          <el-input v-model="listQuery.condition.docCode" @keyup.enter.native="handleFilter" clearable
                    size="small" style="width: 200px" class="filter-item fsc-search" placeholder="单据号">
          </el-input>
          <el-button class="filter-item" size="small" type="primary"
                     v-waves icon="el-icon-search" @click="handleFilter">搜索
          </el-button>
          <el-button class="filter-item" size="small" type="primary"
                     v-waves icon="el-icon-circle-plus-outline" @click="moreCondition">更多
          </el-button>
          <el-dropdown trigger="click" :hide-on-click=false style="float: right;margin-left: 10px">
            <span class="el-dropdown-link">
              <el-button class="filter-item" size="small" type="primary" v-waves>
                选择列<i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <el-checkbox-group v-model="theadCheckVal">
                  <el-checkbox label="businessType">业务类型</el-checkbox>
                  <el-checkbox label="docTypeName">单据类型</el-checkbox>
                  <el-checkbox label="docCode">单据号</el-checkbox>
                  <el-checkbox label="mainCompanyName">主体公司</el-checkbox>
                  <el-checkbox label="buildAccountDate">立账日期</el-checkbox>
                  <el-checkbox label="termAccountDate">到账日期</el-checkbox>
                  <el-checkbox label="originalCurrencySum">金额</el-checkbox>
                  <el-checkbox label="partnerName">供应商</el-checkbox>
                  <el-checkbox label="partnerSname">供应商简称</el-checkbox>
                  <el-checkbox label="status">单据状态</el-checkbox>
                  <el-checkbox label="sourceKey">来源单据标识</el-checkbox>
                  <el-checkbox label="makeDate">制单日期</el-checkbox>
                </el-checkbox-group>
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-col>
      </el-row>
      <div style="clean:both"></div>
    </div>

    <el-collapse-transition>
      <div style="width: 99%; margin: 0px auto;" v-show="searchFlag">
        <div style="height: 10px"></div>
        <el-row>
          <el-col :span="6">
            <span class="condition_common">单据类型: </span>
            <el-select v-model="listQuery.condition.docType" placeholder="请选择"
                       style="width: 200px" class="filter-item fsc-search"
                       :clearable="true"  size="small">
              <el-option
                v-for="item in shouldPaymentTypeList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <span class="condition_common">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;单据号: </span>
            <el-input v-model="listQuery.condition.docCode" size="small"
                      style="width: 200px" class="filter-item fsc-search" placeholder="单据号">
            </el-input>
          </el-col>
          <el-col :span="6">
            <span class="condition_common">立账开始时间: </span>
            <el-date-picker
              v-model="listQuery.condition.startBuildAccountDate"
              type="date"
              value-format="yyyy-MM-dd" format="yyyy-MM-dd"
              size="small" class="filter-item fsc-search"
              placeholder="选择立账开始时间">
            </el-date-picker>
          </el-col>
          <el-col :span="6">
            <span class="condition_common">立账结束时间: </span>
            <el-date-picker
              v-model="listQuery.condition.endBuildAccountDate"
              type="date"
              value-format="yyyy-MM-dd" format="yyyy-MM-dd"
              size="small" class="filter-item fsc-search"
              placeholder="选择立账结束时间">
            </el-date-picker>
          </el-col>
        </el-row>
        <div style="height: 10px"></div>
        <el-row>
          <el-col :span="6">
            <span class="condition_common">主体公司: </span>
            <el-select class="filter-item fsc-search" v-model="listQuery.condition.mainCompanyId" clearable placeholder="请选择"
                       size="small">
              <el-option
                v-for="item in companyList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-col>
          <el-col :span="6">
            <span class="condition_common">来源单据号: </span>
            <el-input v-model="listQuery.condition.sourceKey" size="small"
                      style="width: 200px" class="filter-item fsc-search" placeholder="单据号">
            </el-input>
          </el-col>
        </el-row>
        <div style="height: 10px"></div>
      </div>
    </el-collapse-transition>

    <div style="clean:both"></div>

    <el-table :key='tableKey' ref="multipleTable" :data="list" v-loading="listLoading"
              element-loading-text="给我一点时间" border fit highlight-current-row
              style="width: 100%;margin-top:5px" @selection-change="handleSelectionChange">
      <el-table-column type="selection"></el-table-column>
      <el-table-column align="center" label="id" v-if="false" width="0">
        <template slot-scope="scope">
          <span>{{scope.row.id}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="序号" width="50" fixed="left">
        <template slot-scope="scope">
          <span>{{scope.$index+1}}</span>
        </template>
      </el-table-column>
      <el-table-column :key="key" align="center" v-for='(value,key) in tableThead' :label="value.title" :width="value.width">
        <template slot-scope="scope">
          <div v-if="value.key == 'businessType'">{{scope.row[value.key] | payBusinessTypeFilter}}</div>
          <div v-else-if="value.key == 'status'">{{scope.row[value.key] | shouldPaymentStatus}}</div>
          <div v-else>{{scope.row[value.key]}}</div>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="100" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini" type="primary"
            @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page.sync="listQuery.current"
                     :page-sizes="[10,20,30, 50]" :page-size="listQuery.size"
                     layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 弹框抓取 -->
    <el-dialog title="手动抓取" :visible.sync="freshDialogVisible">
      <el-input
        type="textarea"
        :rows="5"
        placeholder="请输入需要抓取的单号, 以英文逗号(,)或分号(;)隔开"
        v-model="freshErp.freshOrderCodeStr">
      </el-input>
      <div slot="footer" class="dialog-footer">
        <el-button @click="freshDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handFreshOrder">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { queryPage, create, deletedForBatch, update, getShouldPaymentById, confirmShouldPayment } from '@/api/pay/shouldPayment'
  import { freshErpOrder } from '@/api/pay/shouldPaymentFresh'
  import waves from '@/directive/waves'
  import { getShouldPaymentTypeList, getCompanyList } from '@/api/baseDataCommon'
  const defautlTableThead = [
    { key: 'businessType', title: '业务类型', width: 100 },
    { key: 'docTypeName', title: '单据类型', width: 100 },
    { key: 'docCode', title: '单据号', width: 150 },
    { key: 'mainCompanyName', title: '主体公司', width: 290 },
    { key: 'buildAccountDate', title: '立账日期', width: 100 },
    { key: 'termAccountDate', title: '到账日期', width: 100 },
    { key: 'originalCurrencySum', title: '金额', width: 150 },
    { key: 'partnerName', title: '供应商', width: 300 },
    { key: 'partnerSname', title: '供应商简称', width: 300 },
    { key: 'status', title: '单据状态', width: 80 },
    { key: 'sourceKey', title: '来源单据标识', width: 150 },
    { key: 'makeDate', title: '制单日期', width: 100 }
  ]
  export default {
    name: 'shouldPayment',
    directives: {
      waves
    },
    data() {
      return {
        theadCheckVal: [
          'businessType', 'docTypeName', 'docCode', 'mainCompanyName', 'buildAccountDate',
          'termAccountDate', 'originalCurrencySum', 'partnerName', 'partnerSname', 'status', 'sourceKey', 'makeDate'
        ],
        tableThead: defautlTableThead,
        key: 1, // table key
        desc: true,
        tableKey: 0,
        searchFlag: true,
        list: [],
        detailList: [{ 'docCode': '10', 'docType': '25' }],
        shouldPaymentTypeList: null,
        companyList: null,
        multipleSelection: [],
        detailListSelect: [],
        listLoading: true,
        dialogFormVisible: false,
        freshDialogVisible: false,
        freshErp: {
          freshOrderCodeStr: ''
        },
        freshLoad: false,
        total: null,
        listQuery: {
          current: 1,
          size: 10,
          order: '',
          condition: {
            docCode: '',
            docType: '',
            startBuildAccountDate: '',
            endBuildAccountDate: '',
            sourceKey: '',
            mainCompanyId: undefined
          }
        },
        temp: {
          id: undefined,
          docCode: '',
          docType: '',
          docDate: '',
          settlCompanyId: '',
          mainCompanyId: '',
          isInitial: undefined,
          detailList: []
        },
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        rules: {
          docCode: [{ required: true, message: '单据号不能为空', trigger: 'change' }],
          docDate: [{ required: true, message: '立账日期不能为空', trigger: 'change' }],
          mainCompanyId: [{ required: true, message: '主体公司不能为空', trigger: 'change' }],
          settlCompanyId: [{ required: true, message: '结算公司不能为空', trigger: 'change' }],
          stockGoodsId: [{ required: true, message: '存货不能为空', trigger: 'change' }],
          partnerId: [{ required: true, message: '供应商不能为空', trigger: 'change' }],
          qty: [{ required: true, message: '存货不能为空', trigger: 'change' }]
        }
      }
    },
    created() {
      this.getList()
      this.initShouldPaymentList()
      this.initCompanyList()
    },
    watch: {
      theadCheckVal(valArr) {
        this.tableThead = defautlTableThead.filter((v) => {
          for (var i = 0; i < valArr.length; i++) {
            if (v.key === valArr[i]) {
              return v
            }
          }
        })
      }
    },
    methods: {
      // 初始化单据类型
      initShouldPaymentList() {
        getShouldPaymentTypeList().then(response => {
          this.shouldPaymentTypeList = response.data
        })
      },
      // 初始化公司下拉
      initCompanyList() {
        getCompanyList().then(response => {
          this.companyList = response.data
        })
      },
      getShouldPaymentById(selectId) {
        // 获取编辑数据
        getShouldPaymentById(selectId).then(response => {
          // 需要修改的数据
          this.temp = response.data
          this.detailList = response.data.detailList
        })
      },
      getList() {
        this.listLoading = true
        queryPage(this.listQuery).then(response => {
          this.list = response.data.records
          this.total = response.data.total
          this.listLoading = false
        })
      },
      handleFilter() {
        this.listQuery.current = 1
        this.list = null
        this.getList()
      },
      handleEdit(index, row) {
        var selectId = row.id
        getShouldPaymentById(selectId).then(response => {
          // 需要修改的数据
          this.temp = response.data
          this.detailList = response.data.detailList
          this.$router.push({
            path: 'shouldPaymentEdit',
            name: '应付录入',
            params: {
              isUpdate: 1,
              shouldPaymentId: selectId,
              shouldPaymentObj: response.data
            }
          })
        })
      },
      handleCreate() {
        this.resetTemp()
        this.detailList = []
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.temp.detailList = this.detailList
            create(this.temp).then(response => {
              this.dialogFormVisible = false
              this.resetTemp()
              this.getList()
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleUpdate() {
        if (this.multipleSelection.length <= 0) {
          this.warnMessage('请选择要编辑的数据!')
          return
        }
        if (this.multipleSelection.length > 1) {
          this.warnMessage('只能选择一条数据!')
          return
        }
        this.resetTemp()
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      handleConfirm() {
        // 审核
        if (this.multipleSelection.length <= 0) {
          this.warnMessage('请选择要审核的数据!')
          return
        }
        var statusList = this.checkPaymentStatus(0)
        if (statusList.length > 0) {
          this.warnMessage('只有新增状态才可以审核!')
          return
        }
        this.messageUtil('是否确定审核选中的数据?', '已审核', this.handleToConfirm)
      },
      handleToConfirm() {
        // 确定审核
        var ids = []
        this.multipleSelection.forEach(function(item, index, array) {
          ids.push(item.id)
        })
        confirmShouldPayment(ids).then(response => {
          this.getList()
          this.$notify({
            title: '成功',
            message: response.message,
            type: 'success',
            duration: 2000
          })
        })
      },
      handleDelete() {
        if (this.multipleSelection.length <= 0) {
          this.warnMessage('请选择要删除的数据!')
          return
        }
        var statusList = this.checkPaymentStatus(0)
        if (statusList.length > 0) {
          this.warnMessage('只有新增状态才可以删除!')
          return
        }
        this.messageUtil('是否确定删除选中的数据?', '已取消删除', this.handleTrueDelete)
      },
      handleTrueDelete() {
        var ids = []
        this.multipleSelection.forEach(function(item, index, array) {
          ids.push(item.id)
        })
        deletedForBatch(ids).then(response => {
          if (response.code === 0) {
            this.getList()
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          } else {
            this.$notify.error({
              title: '失败',
              message: response.message,
              duration: 2000
            })
          }
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            update(this.temp).then(response => {
              this.dialogFormVisible = false
              this.getList()
              this.$notify({
                title: '成功',
                message: response.message,
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleFresh() {
        // 弹框抓取
        this.freshDialogVisible = true
        this.freshErp.freshOrderCodeStr = ''
      },
      handFreshOrder() {
        // 手动抓取
        this.messageUtil('是否确定抓取输入的单号?', '已取消', this.handleToHandFresh)
      },
      handleToHandFresh() {
        const loading = this.$loading({
          text: '拼命抓取中, 请稍后...',
          spinner: 'el-icon-loading',
          background: 'rgba(255, 255, 255, 0.7)'
        })
        freshErpOrder(this.freshErp).then(response => {
          this.getList()
          this.freshDialogVisible = false
          loading.close()
          if (response.code !== 0 && response.code === -1) {
            this.$notify({
              title: '失败',
              message: response.message,
              type: 'error',
              duration: 2000
            })
          } else {
            this.$notify({
              title: '成功',
              message: response.message,
              type: 'success',
              duration: 2000
            })
          }
        })
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      handleDetailChange(val) {
        // this.detailListSelect = val
        this.detailListSelect = val
      },
      handleSizeChange(val) {
        this.listQuery.size = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.listQuery.current = val
        this.getList()
      },
      resetTemp() {
        this.temp = {
          id: undefined
        }
      },
      moreCondition() {
        this.searchFlag = !this.searchFlag
      },
      warnMessage(message) {
        this.$notify({
          title: '警告',
          message: message,
          type: 'warning',
          duration: 2000
        })
        return
      },
      messageUtil(titleMessage, catchMessage, toFunction) {
        this.$confirm(titleMessage, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          toFunction()
        }).catch(() => {
          this.$message({
            type: 'info',
            message: catchMessage
          })
        })
      },
      checkPaymentStatus(status) {
        // 删除前和审核前校验
        var ids = []
        this.multipleSelection.forEach(function(item, index, array) {
          if (item.status !== status) {
            ids.push(item.id)
          }
        })
        return ids
      }
    }
  }
</script>

<style scoped>
  .condition_common {
    font-size: 14px;
  }
</style>

